#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-10-14 15:53:00
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

import os
import psutil
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class Monitor(object):

    #CPU信息
    def get_cpu_info(self):
        cpu_info={
            'physical_count' : psutil.cpu_count(logical=False), #CPU物理个数
            'logical_count' : psutil.cpu_count(logical=True), #逻辑个数
            'cpu_status' : psutil.cpu_stats(), #CPU状态
            'cpu_time' : psutil.cpu_times(), #cpu时间
            #print self.psutil.cpu_times(percpu=True), #cpu时间
            'cpu_times_percent' : psutil.cpu_times_percent(), #cpu时间占比
            'cpu_percent' : psutil.cpu_percent(interval=3), #3秒内的CPU占比
            'cpu_times_percent_idle' : psutil.cpu_times_percent().idle, #cpu处于空闲时间状态百分比
            #psutil.cpu_percent(interval=5, percpu=True) #5秒内每个CPU占比，percpu=True
            #psutil.cpu_percent(interval=None, percpu=False)
            # 返回一个浮点数，代表当前cpu的利用率的百分比，包括sy+user. 当interval为0或者None时，
            # 表示的是interval时间内的sys的利用率。
            # 当percpu为True返回是每一个cpu的利用率。
        }
        return cpu_info

    #内存信息
    def get_mem_info(self):
        vm = psutil.virtual_memory() #内存
        #svmem(total=8489750528L, available=3208241152L, percent=62.2, used=5281509376L, free=3208241152L)
        swap = psutil.swap_memory() #虚拟内存
        #sswap(total=16977596416L, used=7076675584L, free=9900920832L, percent=41.7, sin=0, sout=0)

        mem_info = {
            'virtual_memory' : {
                'vm_total' : vm.total/1024/1024/1024.0,
                'vm_used' : vm.used/1024/1024/1024.0,
                'vm_available' : vm.available/1024/1024/1024.0, #可用内存，同free
                'vm_free' :vm.free/1024/1024/1024.0,
                'vm_percent' : vm.percent
            },
            'swap' : {
                'swap_total' : swap.total/1024/1024/1024.0,
                'swap_used' : swap.used/1024/1024/1024.0,
                'swap_free' : swap.free/1024/1024/1024.0,
                'swap_percent' : swap.percent/1024/1024/1024.0
            }
        }
        return mem_info

    #磁盘信息
    def get_disk_info(self):
        disk_info = {}
        #print psutil.disk_partitions(all=False) #磁盘信息
        #print psutil.disk_usage('C:')
        #print psutil.disk_io_counters(perdisk=False) #返回当前磁盘的io情况
        try:
            for i in psutil.disk_partitions():
                disk = i[0][0] # E:\
                #print(psutil.disk_usage(i[1])) # 磁盘使用情况
                disk_usage = psutil.disk_usage(i[1])
                # print('%s 使用情况如下: ' % i[1])
                # print('----------分区总大小：%.1fG' % (disk_usage[0]/1024/1024/1024))
                # print('----------已使用空间：%.1fG' % (disk_usage[1]/1024/1024/1024))
                # print('----------剩余空间：  %.1fG' % (disk_usage[2]/1024/1024/1024))
                disk_info[disk] = {
                    'total' : disk_usage[0]/1024/1024/1024,
                    'used' : disk_usage[1]/1024/1024/1024,
                    'free' : disk_usage[2]/1024/1024/1024
                }
        except Exception, e:
            print e
        return disk_info

    def get_network_info(self):   #获取网络信息
        self.net_info={}
        self.network = psutil.net_io_counters()
        print 'network:',self.network
        # print('已发送字节数：%.1fM' % (self.network[0]/1024/1024/1024))
        # print('已接收字节数：%.1fM' % (self.network[1]/1024/1024/1024))
        # print('已发送数据包个数：%.1f' % self.network[2])
        # print('已接收数据包个数：%.1f' % self.network[3])
        self.net_info['bytes_sent'] = self.network[0]/1024/1024/1024
        self.net_info['bytes_recv'] = self.network[1]/1024/1024/1024
        self.net_info['packets_sent'] = self.network[2]
        self.net_info['packets_recv'] = self.network[2]
        return self.net_info


    def get_user_info(self):    #获取用户信息
        print('系统开机时间为：%s' % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S'))
        self.user = psutil.users()
        for i in range(0,len(self.user)):
            print('用户名 ：%s,终端 ：%s,主机 ：%s，登录时间 %s' %(self.user[i][0],self.user[i][1],self.user[i][2],datetime.datetime.fromtimestamp(self.user[i][3]).strftime('%Y-%m-%d %H:%M:%S')))

    def get_all_info(self):
        result = {}
        mems = self.get_mem_info()
        cpus = self.get_cpu_info()
        result['mems'] = mems
        result['cpus'] = cpus
        return result

if __name__ == '__main__':
    m = Monitor()
    print m.get_cpu_info()
    print m.get_mem_info()
    print m.get_disk_info()
    print m.get_network_info()
    print m.get_user_info()
